package pl.edu.mimuw.irs.rcp.view.navigation;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;

import pl.edu.mimuw.irs.rcp.util.Logger;
import pl.edu.mimuw.irs.rcp.util.MessageCode;

public class NavigationViewContentProvider implements IStructuredContentProvider, 
ITreeContentProvider {

    public void inputChanged(Viewer v, Object oldInput, Object newInput) {
	}
    
	public void dispose() {
	}
    
	public Object[] getElements(Object parent) {
		return getChildren(parent);
	}
    
	public Object getParent(Object child) {
		if (child instanceof IWorkspaceRoot) {
			return ((IWorkspaceRoot) child).getParent();
		} else if (child instanceof IProject) {
			return ((IProject) child).getParent();
		} else if (child instanceof IResource) {
			return ((IResource) child).getParent();
		} else {
			return null;
		}
	}
    
	public Object[] getChildren(Object parent) {
		if (parent instanceof IWorkspaceRoot) {
			IWorkspaceRoot rootWorkspace = (IWorkspaceRoot)parent;
			return rootWorkspace.getProjects();
		} else if (parent instanceof IProject) {
			IProject project = (IProject)parent;
			try {
				if (project.isOpen()) return project.members();
				else return new Object[0];
			} catch (CoreException e) {
				Logger.handle(MessageCode.PROJECT_OPEN_PROBLEM, e, project.getName());
				return new Object[0];
			}
		} else if (parent instanceof IResource) {
			//IResource resource = (IResource)parent;
			return new Object[0];
		} else {
			return new Object[0];
		}
		
	}

    public boolean hasChildren(Object parent) {
    	if (parent instanceof IWorkspaceRoot) {
			IWorkspaceRoot rootWorkspace = (IWorkspaceRoot)parent;
			return rootWorkspace.getProjects().length > 0;
		} else if (parent instanceof IProject) {
			IProject project = (IProject)parent;
			try {
				if (project.isOpen()) return project.members().length > 0;
				else return false;
			} catch (CoreException e) {
				Logger.handle(MessageCode.PROJECT_OPEN_PROBLEM, e, project.getName());
				return false;
			}
		} else if (parent instanceof IResource) {
			//IResource resource = (IResource)parent;
			return false;
		} else {
			return false;
		}
	}
}

